package org.munoz.client;

import java.util.logging.Logger;
import java.util.logging.Level;

import org.munoz.client.gwtfb.sdk.FBCore;
import org.munoz.client.gwtfb.sdk.FBEvent;
import org.munoz.client.gwtfb.sdk.FBXfbml;
import org.munoz.shared.LoginInfo;
import org.munoz.shared.State;

import com.google.gwt.appengine.channel.client.Channel;
import com.google.gwt.appengine.channel.client.ChannelError;
import com.google.gwt.appengine.channel.client.ChannelFactoryImpl;
import com.google.gwt.appengine.channel.client.SocketListener;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.dom.client.Style.Display;
import com.google.gwt.dom.client.Style.VerticalAlign;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.storage.client.Storage;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.HasRpcToken;
import com.google.gwt.user.client.rpc.RpcTokenException;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.rpc.XsrfToken;
import com.google.gwt.user.client.rpc.XsrfTokenService;
import com.google.gwt.user.client.rpc.XsrfTokenServiceAsync;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.VerticalPanel;
/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class GoFishEntryPoint implements EntryPoint {
//	private LoginServiceAsync loginService;
	private GoFishServiceAsync goFishService;
	private LoginInfo loginInfo = null;
	private Presenter presenter;
	private static final String fbKey = "599704113435077";
    private FBCore fbCore; // = GWT.create(FBCore.class);
    private FBEvent fbEvent; //  = GWT.create(FBEvent.class);
    private boolean fbStatus = true;
    private boolean fbXfbml = true;
    private boolean fbCookie = true;
    
    private Logger logger = Logger.getLogger("");
    
    
    private Label loginL = new Label("Please login");
    private VerticalPanel fbPanel = new VerticalPanel();
    private Anchor linkSignIn = new Anchor("Login");
    
	/**
	 * This is the entry point method.
	 */
	@Override
	public void onModuleLoad() {
		Cookies.setCookie("JSESSIONID", "JSESSIONID", null, null, "/", false);

		loginInfo = new LoginInfo();
				
        XsrfTokenServiceAsync xsrf = (XsrfTokenServiceAsync) GWT
                        .create(XsrfTokenService.class);
        ((ServiceDefTarget) xsrf).setServiceEntryPoint(GWT.getModuleBaseURL()
                        + "xsrf");
        xsrf.getNewXsrfToken(new AsyncCallback<XsrfToken>(){
			@Override
			public void onFailure(Throwable caught) {
				try {
                    throw caught;
				} catch (RpcTokenException e) {
                    GWT.log("Failed to call XSRF protected login service : "
                                    + e.getMessage());
				} catch (Throwable e) {
                    GWT.log("Failed to call XSRF protected login service : "
                                    + e.getMessage());
				}
			}
			@Override
			public void onSuccess(XsrfToken result) {
				goFishService = GWT.create(GoFishService.class);
				((HasRpcToken) goFishService).setRpcToken(result);
				
				fbCore = new FBCore();
				
				fbCore.init(fbKey, fbStatus, fbCookie, fbXfbml);
				
		        //fbEvent.subscribe("auth.statusChange", new SessionChangeCallback());
		        GWT.log("About to contact facebook");
//		        fbCore.getLoginStatus(new LoginStatusCallback());
		        fbCore.getLoginStatus(new AsyncCallback<JavaScriptObject>(){
					@Override
					public void onFailure(Throwable caught) {
						GWT.log("Failure");
					}

					@Override
					public void onSuccess(JavaScriptObject result) {
						GWT.log("Success");
						processFBStatus(result);
					}
		        	
		        });
		        
		        
		        GWT.log("Xsrf protection was deployed successfully.");
		        logger.log(Level.INFO, "XSRF protection enabled");
			}
        });
		
	}
	
	private void processFBStatus(JavaScriptObject result){
		GWT.log("Parsing login status");
    	JSONObject json = new JSONObject(result);
        String fbStatus = json.get("status").toString().replace("\"", "");
		GWT.log(fbStatus);
        if(fbStatus.compareTo("connected") == 0){
        	loginInfo.setLoggedIn(true);
        	JSONObject auth = (JSONObject) json.get("authResponse");
        	loginInfo.setUserFBId(auth.get("userID").toString().replace("\"", ""));
        	loginInfo.setFBAccessToken(auth.get("accessToken").toString());
        	//hideFBLogin();
        	getUserName();
        }
        else{
        	GWT.log("Displaying login button");
        	displayFBLogin();
        }
	}
	
	private void getUserName(){
		fbCore.api("/me?fields=first_name", new AsyncCallback<JavaScriptObject>(){

			@Override
			public void onFailure(Throwable caught) {
				GWT.log("Error getting user name");
			}

			@Override
			public void onSuccess(JavaScriptObject result) {
				JSONObject json = new JSONObject(result);
				String userN = json.get("first_name").toString().replace("\"", "");
				GWT.log(userN);
				loginInfo.setFBUserName(userN);

				Graphics graphics = new Graphics();
				presenter = new Presenter(goFishService, graphics, loginInfo); 
				RootPanel.get().add(graphics);
			}
			
		});
	}
	
	private void hideFBLogin(){
		// TODO
	}
	private void displayFBLogin(){
        
        fbPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
        fbPanel.setWidth("100%");
        fbPanel.getElement().getStyle()
                        .setVerticalAlign(VerticalAlign.MIDDLE);
        SimplePanel anchorHolder = new SimplePanel();
        anchorHolder.setStyleName("loginAnchor");
        anchorHolder.add(linkSignIn);
        fbPanel.add(loginL);
        HTML fbLoginButton = new HTML(
                        "<fb:login-button width=\"200\" onlogin=\"window.location.reload()\"></fb:login-button>");
        SimplePanel fbButtonPanel = new SimplePanel();
        fbButtonPanel.add(fbLoginButton);
        fbPanel.add(fbButtonPanel);
        RootPanel.get("fbDialog").add(fbPanel);
        DOM.getElementById("fbDiv").getStyle()
                        .setDisplay(Display.BLOCK);
        DOM.getElementById("fbDialog").getStyle().setDisplay(Display.BLOCK);
        FBXfbml.parse(fbButtonPanel);
 	}

} 




/**
 * Class that creates a panel for local storage
 * @author jpm
 *
 */
class MyLoadPanel extends PopupPanel{
    public MyLoadPanel(final Storage stockstore,final Presenter p,final int c){
        VerticalPanel vp=new VerticalPanel();
        vp.setSpacing(8);
        String msg="";
        if(c==0) msg ="Do you want to Save the Game?";
        else if (c==1) msg ="Load last Game?";
        else if (c==2) msg = "Clear the saved Game?";
	    Label l = new Label(msg);
	    HorizontalPanel buttons = new HorizontalPanel();
	    Button ok =new Button("Ok");
	    Button cancel = new Button("Cancel");
	    buttons.add(ok);
	    buttons.add(cancel);
	    ok.addClickHandler(new ClickHandler(){
	    	@Override
            public void onClick(ClickEvent event) {
                    if(c==0){
                    	if (stockstore != null) {
                            String k =  State.serializeState(p.getState()); //Presenter.Seralize(p.getState());
                            int numStocks = stockstore.getLength();
                            if(numStocks==0) stockstore.setItem("Stock."+numStocks, k);
                            else{
                                    stockstore.clear();
                                    stockstore.setItem("Stock."+numStocks, k);
                            }
                
                    }
                    MyLoadPanel.this.hide();
                    }else if(c==1){
                    	if (stockstore != null) {
                            String key = stockstore.key(0);
                            String k = stockstore.getItem(key);
                            State st = State.unserializeState(k);
                            p.setState(st);
                            MyLoadPanel.this.hide();
//                            p.addHistory();
                    	}else MyLoadPanel.this.hide();
                    	}else {
                            stockstore.clear();
                            MyLoadPanel.this.hide();
                    	}
                    
            		}
	    	});
	    cancel.addClickHandler(new ClickHandler(){
            @Override
            public void onClick(ClickEvent event) {
                    MyLoadPanel.this.hide();
            }
	    });
	    vp.add(l);
	    vp.add(buttons);
	    this.setGlassEnabled(true);
	    this.setAnimationEnabled(true);
	    this.setWidget(vp);
    }
    
    

}





